package com.zw.pm.util;


import com.zw.pm.config.shiro.realm.ShiroRealm;
import com.zw.pm.gen.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * @Description: shiro 工具类
 *
 * @Author: China.sgl
 * @Date: 2019/9/9 14:15
 */
public class ShiroUtils {

    /**
     * 获取 Subject
     *
     * @return Subject
     */
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * 获取 Session
     *
     * @return Session
     */
    public static Session getSession() {
        return getSubject().getSession();
    }

    /**
     * 获取登录用户
     *
     * @return 登录用户
     */
    public static User getUser() {
        return (User) getSession().getAttribute("user");
    }

    /**
     * 清空缓存
     */
    public static void clearCachedAuthorizationInfo() {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        ShiroRealm realm = (ShiroRealm) rsm.getRealms().iterator().next();
        realm.clearCachedAuthorizationInfo();
    }

    /**
     * 获取登录用户ID
     *
     * @return id
     */
    public static Integer getUserId() {
        return getUser().getId();
    }

    /**
     * 获取登录帐号
     *
     * @return 帐号
     */
    public static String getLoginName() {
        return getUser().getAccount();
    }

    /**
     * 获取 IP
     *
     * @return IP
     */
    public static String getIp() {
        return getSession().getHost();
    }

    /**
     * 获取sessionID
     *
     * @return sessionID
     */
    public static String getSessionId() {
        return String.valueOf(getSession().getId());
    }

}
